﻿using OnlineMealOrdering.Common;
using OnlineMealOrdering.Domain.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OnlineMealOrdering.Domain
{
    public class FoodCatalogEntity : AuditableEntity
    {
        //类别的拼音
        public string ShortName { get; set; }

        public string Name { get; set; }

        public int SortNo { get; set; }

        public virtual ICollection<FoodEntity> Foods { get; set; }

        public virtual FoodCatalogEntity Parent { get; set; }

        public bool Enable { get; set; }

        public static FoodCatalogEntity Create(string name, int? parent, int sortNo = 0, bool enable = true)
        {
            var entity = new FoodCatalogEntity();

            var catalog = DomainContext.Current.EntitySet<FoodCatalogEntity>().SingleOrDefault(a => a.Id == parent.Value);

            entity.Name = name;
            entity.SortNo = sortNo;
            entity.Parent = catalog;
            entity.Enable = enable;
            return entity;
        }

        public void Update(int id, string name, int sortNo = 0, bool enable = true)
        {
            var catalog = DomainContext.Current.EntitySet<FoodCatalogEntity>().SingleOrDefault(a => a.Id == id);
            catalog.Name = name;
            catalog.SortNo = sortNo;
            catalog.Enable = enable;
            catalog.Name = name;
        }

        public FoodEntity AddFood(string name, decimal costPrice, decimal price, int storeid, int catalogId, bool recommed,List<FoodEntity> gift, List<ImageEntity> imgelist)
        {
            if (Foods == null)
                Foods = new List<FoodEntity>();
            var entity = FoodEntity.Create(name, costPrice, price, storeid, catalogId, recommed,gift, imgelist);
            this.Foods.Add(entity);
            return entity;
        }

        

        public static void Delete(int id)
        {
            var entity = DomainContext.Current.EntitySet<FoodCatalogEntity>().SingleOrDefault(a => a.Id == id);
            if (entity.Foods.Count > 0)
                BusinessException.Create("该类目存在餐品不能删除！ID:{0}", id);

            var catalogChilds = DomainContext.Current.EntitySet<FoodCatalogEntity>().Any(a => a.Parent.Id == id);
            if (catalogChilds)
                BusinessException.Create("该类目存在子类不能删除！ID:{0}", id);

            DomainContext.Current.Remove<FoodCatalogEntity>(entity);
            DomainContext.Current.SubmitChanges();
        }

        public void DeleteProduct(int id)
        {
            var entity = Foods.Single(a => a.Id == id);
            if (entity == null)
                BusinessException.Create("找不到餐品ID:{0}", id);
            Foods.Remove(entity);
            DomainContext.Current.SubmitChanges();
        }



    }
}
